<template>
  <div>
    <h3>教职员查询</h3>
    <div class="container">
      <vxe-toolbar style="height: 100px;">
        <template #buttons>
          <el-row :gutter="20" type="flex" style="margin-bottom: 20px;">
            <el-col :span="4">
              <el-select v-model="searchForm.areaId" size="small" collapse-tags filterable clearable placeholder="选择区域"
                @change="areaChange">
                <el-option :label="item.name" :value="item.areaId" v-for="(item,index) in areaData"
                  :key="index"></el-option>
              </el-select>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-select v-model="searchForm.orgIdStr" size="small" multiple collapse-tags filterable clearable
                placeholder="选择组织机构">
                <el-option :label="item.name" :value="item.orgId" v-for="(item,index) in orgData"
                  :key="index"></el-option>
              </el-select>
              <el-button type="success" size="small" @click="selectOrgAll">全选</el-button>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-select v-model="searchForm.empTypeIdStr" size="small" multiple collapse-tags filterable clearable
                placeholder="选择工作类型">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_employee_type"
                  :key="index"></el-option>
              </el-select>
              <el-button type="success" size="small"
                @click="searchForm.empTypeIdStr=Object.keys(dict_employee_type)">全选</el-button>
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchForm.sportId" size="small" :disabled="sportDisabled" collapse-tags filterable
                clearable placeholder="选择运动项目" @change="sportChange">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_sport" :key="index"></el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchForm.sportItemId" size="small" :disabled="Object.keys(sportItemData).length==0"
                collapse-tags filterable clearable placeholder="选择运动小项">
                <el-option :label="item" :value="key" v-for="(item,key,index) in sportItemData"
                  :key="index"></el-option>
              </el-select>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-select v-model="searchForm.ageStr" size="small" multiple collapse-tags filterable clearable
                placeholder="选择年龄">
                <el-option v-show="item>=15" :label="item+'岁'" :value="item" v-for="(item,index) in 85"
                  :key="index"></el-option>
              </el-select>
              <el-button type="success" size="small" @click="selectAgeAll">全选</el-button>
            </el-col>
          </el-row>
          <el-row :gutter="20" type="flex">
            <el-col :span="4" style="display: flex;">
              <el-button @click="exportEvent" size="small" type="primary" icon="el-icon-download">导出</el-button>
              <el-button @click="printEvent" size="small" type="primary" icon="el-icon-printer">打印</el-button>
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchForm.professionTypeId" size="small" collapse-tags filterable clearable
                placeholder="选择职位/职务 ">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_profession_type"
                  :key="index"></el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchForm.empStatusId" size="small" collapse-tags filterable clearable
                placeholder="选择在职状态">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_status" :key="index"></el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-date-picker size="small" v-model="doubleDate" type="daterange" align="right" unlink-panels
                style="width: 90%;" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-button type="success" size="small" icon="el-icon-s-promotion" @click="searchSubmit"
                style="margin: 0 10px;"> 搜索</el-button>
              <vxe-button @click="clearTableFilter" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
            </el-col>
            <el-col :span="4">
              <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
                @keyup="searchEvent"></vxe-input>
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="XTable" show-overflow border max-height="800" stripe highlight-hover-row
        highlight-current-row :loading="loading" :data="dataList">
        <vxe-table-column field="name" title="姓名" sortable></vxe-table-column>
        <vxe-table-column field="idNo" title="身份证" sortable></vxe-table-column>
        <vxe-table-column field="gender" title="性别" sortable></vxe-table-column>
        <vxe-table-column field="age" title="年龄" sortable></vxe-table-column>
        <vxe-table-column field="empType" title="专职" sortable></vxe-table-column>
        <vxe-table-column field="heightName" title="兼职" sortable></vxe-table-column>
        <vxe-table-column field="workDate" title="入职时间" sortable></vxe-table-column>
        <vxe-table-column field="teachDate" title="执教时间" sortable></vxe-table-column>
        <vxe-table-column field="leaveDate" title="离职时间" sortable></vxe-table-column>
        <vxe-table-column field="professionType" title="职位/职务" sortable></vxe-table-column>
        <vxe-table-column field="empStatus" title="在职状态" sortable></vxe-table-column>
        <vxe-table-column field="sport" title="运动项目" sortable></vxe-table-column>
        <vxe-table-column field="sportItem" title="运动小项" sortable></vxe-table-column>
        <vxe-table-column field="org" title="组织机构" sortable></vxe-table-column>
        <vxe-table-column field="" title="操作" width="100">
          <template #default="{ row }">
            <el-link @click="empDetail(row)" type="primary">查看档案</el-link>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.pageNum" :page-size="page.pageSize" :total="page.totalResult"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
      </vxe-pager>
    </div>
    <vxe-modal v-model="printModal" title="档案预览" height="80%" show-zoom resize width="800" show-footer>
      <template #default>
        <div>
          <empDetailPrint ref="detailPrint" :detailData="detailData" />
        </div>
      </template>
      <template #footer>
        <el-button @click="printModal=false" type="warning" size="mini">关闭</el-button>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
  import {
    statistics_org4provence,
    statistics_area,
    empId2pId,
    sport_all,
    sport_item_all,
    emp_name_list,
    emp_name_list_select
  } from '@/api/statistics.js'
  import { employee_type, profession_type, employee_status, getWage_level, by_sportId } from '@/api/dict.js'
  import { getDetail } from '@/api/person.js'
  import empDetailPrint from '@/components/print/empDetailPrint.vue'
  export default {
    components: { empDetailPrint },
    data() {
      return {
        doubleDate: '',
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        defaultDataList: [],
        dataList: [],
        page: {
          pageNum: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        searchProps: [],
        dict_org: {},
        areaData: [],
        dict_person: {},
        dict_employee_type: {},
        dict_profession_type: {},
        dict_employee_status: {},
        dict_getWage_level: {},
        dict_status: { 1: '开通', 2: '审核', 3: '关闭' },
        dict_sport: {},
        dict_sport_item: {},
        searchForm: {
          areaId: '',
          empTypeIdStr: [],
          ageStr: [],
          orgIdStr: [],
          professionTypeId: '',
          empStatusId: '',
          sportId: '',
          sportItemId: '',
          startDate: '',
          endDate: '',
        },
        orgData: [],
        sportItemData: {},
        printModal: false,
        detailData: {},
      }
    },
    created() {
      this.init_dict().then(() => {
        this.getOrg4emp()
      })
    },
    computed: {
      sportDisabled() {
        if (this.searchForm.empTypeIdStr.length == 1 && this.searchForm.empTypeIdStr[0] == '1') {
          return false
        } else {
          return true
        }
      },
    },
    methods: {
      empDetail(row) {
        getDetail({ pId: row.pid, data: { orgId: row.orgId } }).then(res => {
          if (res.code === 200) {
            this.detailData = res.data
            this.printModal = true
          } else {
            this.detailData = {}
          }
        })

      },
      searchSubmit() {
        let data = {}
        if (this.searchForm.empTypeIdStr.length != 0) data.empTypeIdStr = this.searchForm.empTypeIdStr.join(',')
        if (this.searchForm.ageStr.length != 0) data.ageStr = this.searchForm.ageStr.join(',')
        if (this.searchForm.orgIdStr.length != 0) data.orgIdStr = this.searchForm.orgIdStr.join(',')
        if (this.searchForm.professionTypeId) data.professionTypeId = this.searchForm.professionTypeId
        if (this.searchForm.empStatusId) data.empStatusId = this.searchForm.empStatusId
        if (this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if (this.searchForm.sportItemId) data.sportItemId = this.searchForm.sportItemId
        if (this.doubleDate) {
          data.startDate = this.$moment(this.doubleDate[0]).format('YYYY-MM-DD') + ' 00:00:00'
          data.endDate = this.$moment(this.doubleDate[1]).format('YYYY-MM-DD') + ' 00:00:00'
        }

        data.pageNum = 1
        data.pageSize = this.page.pageSize
        emp_name_list_select(data).then(res => {
          if (res.code === 200) {
            this.init_data(res.data.employeeSports)
            this.page.totalResult = res.data.countNum
          } else {
            this.defaultDataList = []
          }
        }).then(() => {
          // this.findList()
        })
      },
      clearTableFilter() {
        this.searchForm = {
          areaId: '',
          empTypeIdStr: [],
          ageStr: [],
          orgIdStr: [],
          professionTypeId: '',
          empStatusId: '',
          sportId: '',
          sportItemId: '',
          startDate: '',
          endDate: '',
        }
        this.page.pageNum = 1,
          this.page.pageSize = 10
        this.doubleDate = ''
        this.getOrg4emp()
      },
      selectAgeAll() {
        this.searchForm.ageStr = []
        for (var i = 15; i <= 85; i++) {
          this.searchForm.ageStr.push(i)
        }
      },
      sportChange(val) {
        this.searchForm.sportItemId = ''
        this.sportItemData = {}
        by_sportId({ sportId: val }).then(res => {
          this.sportItemData = res
        })
      },
      selectOrgAll() {
        this.searchForm.orgIdStr = []
        this.orgData.forEach(item => {
          this.searchForm.orgIdStr.push(item.orgId)
        })
      },
      areaChange(val) {
        this.orgData = []
        this.searchForm.orgIdStr = ''
        statistics_org4provence({ areaId: val }).then(res => {
          this.orgData = res.data
        })
      },
      getOrg4emp() {
        let data = {}
        if (this.searchForm.empTypeIdStr.length != 0) data.empTypeIdStr = this.searchForm.empTypeIdStr.join(',')
        if (this.searchForm.ageStr.length != 0) data.ageStr = this.searchForm.ageStr.join(',')
        if (this.searchForm.orgIdStr.length != 0) data.orgIdStr = this.searchForm.orgIdStr.join(',')
        if (this.searchForm.professionTypeId) data.professionTypeId = this.searchForm.professionTypeId
        if (this.searchForm.empStatusId) data.empStatusId = this.searchForm.empStatusId
        if (this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if (this.searchForm.sportItemId) data.sportItemId = this.searchForm.sportItemId
        if (this.doubleDate) {
          data.startDate = this.$moment(this.doubleDate[0]).format('YYYY-MM-DD') + ' 00:00:00'
          data.endDate = this.$moment(this.doubleDate[1]).format('YYYY-MM-DD') + ' 00:00:00'
        }

        data.pageNum = this.page.pageNum
        data.pageSize = this.page.pageSize
        emp_name_list_select(data).then(res => {
          if (res.code === 200) {
            this.init_data(res.data.employeeSports)
            this.page.totalResult = res.data.countNum
          } else {
            this.defaultDataList = []
          }
        }).then(() => {
          // this.findList()
        })
      },
      init_data(data) {
        data.forEach(item => {
          item.idNo = this.dict_person[item.pid]
          item.gender = item.genderId == 1 ? '男' : '女'
          item.empType = this.dict_employee_type[item.empTypeId]
          if (item.height) {
            let arr = item.height.split(',')
            let harr = []
            arr.forEach(h => {
              harr.push(this.dict_employee_type[h])
            })
            item.heightName = harr.join(',')
          }
          item.workDate = this.$moment(item.workDate).format('YYYY-MM-DD') == 'Invalid date' ? '' : this.$moment(
            item.workDate).format('YYYY-MM-DD')
          item.teachDate = this.$moment(item.teachDate).format('YYYY-MM-DD') == 'Invalid date' ? '' : this.$moment(
            item.teachDate).format('YYYY-MM-DD')
          item.leaveDate = this.$moment(item.leaveDate).format('YYYY-MM-DD') == 'Invalid date' ? '' : this.$moment(
            item.leaveDate).format('YYYY-MM-DD')
          item.professionType = this.dict_profession_type[item.professionTypeId]
          item.empStatus = this.dict_status[item.empStatusId]
          item.sport = this.dict_sport[item.sportId]
          item.sportItem = this.dict_sport_item[item.sportItemId]
          item.org = this.dict_org[item.orgId]
        })
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data
        this.dataList = this.defaultDataList
      },
      init_dict() {
        return new Promise((resolve, reject) => {
          statistics_org4provence().then(res => {
            this.orgData = res.data
            res.data.forEach(item => {
              this.dict_org[item.orgId] = item.name
            })
          })
          statistics_area().then(res => {
            this.areaData = res.data
          })
          empId2pId().then(res => {
            res.data.forEach(item => {
              this.dict_person[item.pid] = item.idNo
            })
          })
          employee_type().then(res => {
            this.dict_employee_type = res
          })
          profession_type().then(res => {
            this.dict_profession_type = res
          })
          employee_status().then(res => {
            this.dict_employee_status = res
          })
          getWage_level().then(res => {
            this.dict_getWage_level = res
          })
          sport_all().then(res => {
            res.data.forEach(item => {
              this.dict_sport[item.sportId] = item.name
            })
          })
          sport_item_all().then(res => {
            res.data.forEach(item => {
              this.dict_sport_item[item.sportItemId] = item.name
            })
            resolve()
          })
        })
      },
      exportEvent() {
        this.loading = true
        setTimeout(() => {
          this.$refs.XTable.exportData({
            filename: '教职员',
            isHeader: true,
            isFooter: true,
            data: this.defaultDataList
          })
          this.loading = false
        }, 100)
      },
      printEvent() {
        let topHtml = '<h2>教职员</h2>'
        let num = this.page.pageSize
        this.page.pageSize = this.defaultDataList.length
        this.findList()
        setTimeout(() => {
          this.$refs.XTable.print({
            sheetName: '教职员',
            beforePrintMethod: ({ content }) => {
              return topHtml + content
            }
          })
          this.page.pageSize = num
          // this.findList()
        }, 1000)
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = new RegExp(filterName, 'gi')
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
        } else {
          this.dataList = this.defaultDataList
          // this.findList()
        }
      },
      //分页
      handlePageChange({
        currentPage,
        pageSize
      }) {

        this.page.pageNum = currentPage
        this.page.pageSize = pageSize

        this.getOrg4emp()
      },
      // sortChange() {
      //   this.page.pageSize = this.defaultDataList.length
      //   // this.findList()
      // },
      // findList() {
      //   this.loading = true
      //   setTimeout(() => {
      //     this.loading = false
      //     this.page.totalResult = this.defaultDataList.length
      //     this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
      //       .pageSize, this.page.currentPage * this.page.pageSize)
      //   }, 300)
      // },
    }
  }
</script>

<style lang="scss" scoped>
  .container {
    padding: 10px;
    background-color: #FFFFFF;
  }
</style>
